let requestCompleteHandlers = [];
let requestLoadingCount = 0; //显示loading的次数，用户判定何时hideLoading
// 导入websocket模块，用于登录成功后建立连接
let chatIM = null;
try {
	chatIM = require('./websocket.js');
} catch (e) {
	console.log('导入websocket模块失败:', e);
}

// 统一处理图片URL，确保都使用 https://admin.mosizp.cn 域名
function formatImageUrl(url) {
	if (!url || typeof url !== 'string') return url;

	// 如果已经是完整的 https://admin.mosizp.cn 开头的URL，直接返回
	if (url.indexOf('https://admin.mosizp.cn') === 0) {
		return url;
	}

	// 如果是其他域名的URL，替换域名
	if (url.indexOf('http://') === 0 || url.indexOf('https://') === 0) {
		try {
			// 提取路径部分
			const urlMatch = url.match(/https?:\/\/[^\/]+(\/.*)/);
			if (urlMatch && urlMatch[1]) {
				return 'https://admin.mosizp.cn' + urlMatch[1];
			}
		} catch (e) {
			console.log('处理URL失败:', e);
		}
	}

	// 如果是相对路径，直接拼接
	if (url.indexOf('/') === 0) {
		return 'https://admin.mosizp.cn' + url;
	}

	// 其他情况，加上斜杠拼接
	return 'https://admin.mosizp.cn/' + url;
}

// 递归处理对象中的所有图片URL
function processImageUrls(obj) {
	if (!obj) return obj;

	// 图片字段名列表（可以根据实际情况添加更多）
	const imageFields = [
		'image', 'images', 'img', 'imgs', 'avatar', 'avatars',
		'pic', 'pics', 'picture', 'pictures', 'photo', 'photos',
		'thumb', 'thumbnail', 'cover', 'icon', 'logo', 'banner',
		'background', 'bg', 'poster', 'head_img', 'head_pic',
		'file', 'files', 'attachment', 'attachments', 'url',
		'src', 'source', 'path', 'filepath'
	];

	// 如果是字符串，检查是否是图片URL
	if (typeof obj === 'string') {
		// 检查是否是图片文件或包含图片域名
		if (/\.(jpg|jpeg|png|gif|webp|svg|ico|bmp)/i.test(obj) ||
			/^(http|https):\/\//.test(obj)) {
			return formatImageUrl(obj);
		}
		return obj;
	}

	// 如果是数组，递归处理每个元素
	if (Array.isArray(obj)) {
		return obj.map(item => processImageUrls(item));
	}

	// 如果是对象，递归处理每个属性
	if (typeof obj === 'object' && obj !== null) {
		const result = {};
		for (let key in obj) {
			if (obj.hasOwnProperty(key)) {
				// 检查是否是图片相关字段
				const keyLower = key.toLowerCase();
				const isImageField = imageFields.some(field => keyLower.includes(field));

				if (isImageField && typeof obj[key] === 'string') {
					// 处理单个图片URL
					result[key] = formatImageUrl(obj[key]);
				} else if (isImageField && Array.isArray(obj[key])) {
					// 处理图片URL数组
					result[key] = obj[key].map(url => typeof url === 'string' ? formatImageUrl(url) : processImageUrls(url));
				} else {
					// 递归处理其他字段
					result[key] = processImageUrls(obj[key]);
				}
			}
		}
		return result;
	}

	return obj;
}

module.exports = {
	/**
	 * Make request with session info
	 * @param obj Object url, method, data, success, fail
	 */
	request: function(obj) {
		let userinfo = this.getCache('userinfo'),
			currentCity = this.getCurrentCity(),
			currentDistrict = this.getCurrentDistrict();
		obj.header = obj.header || {};
		obj.header.cityid = currentCity.id;
		if (userinfo) {
			obj.header.token = userinfo.token;
		}
		if (!/^http/.test(obj.url)) {
			obj.url = getApp({
				allowDefault: true
			}).globalData.apiBaseUri + (/^\//.test(obj.url) ? obj.url : '/' + obj.url);
		}
		let successCall = obj.success;
		let failCall = obj.fail;
		let that = this;
		obj.success = function(res) {
			if (typeof res.data !== 'object' || res.data.code !== 1) {
				// 如果响应内容非json 或code不为1， 视为失败
				if (res.data.code == 401) {
					that.logout();
					// 使用reLaunch清空页面栈，强制跳转到登录页
					uni.reLaunch({
						url: '/pages/public/login'
					})
				} else {
					obj.fail(res);
				}
				return;
			}

			// 自动处理响应数据中的所有图片URL
			if (res.data && res.data.data) {
				res.data.data = processImageUrls(res.data.data);
			}

			if (typeof successCall === 'function') {
				setTimeout(() => {
					successCall(res.data, res);
				}, 1);

			}
		};
		obj.fail = function(res) {
			setTimeout(() => {
				let showMsg = true;
				//console.log(typeof failCall)
				if (typeof failCall === 'function') {
					showMsg = failCall(res.data, res);
				}
				if (showMsg !== false) {
					uni.showToast({
						'title': (res.data ? res.data.msg || '网络错误' : '网络错误'),
						icon: "none"
					})
				}
			}, 1);
		};
		obj.complete = function(res) {
			if (obj.loading !== false) {
				if (--requestLoadingCount <= 0) {
					requestLoadingCount = 0;
					uni.hideLoading();
				}

			}
			for (let i in requestCompleteHandlers) {
				if (typeof requestCompleteHandlers[i] === 'function') {
					requestCompleteHandlers[i].apply(this, [res.data, res]);
				}
			}
		};
		if (obj.loading !== false) {
			//转菊花，遮蔽操作
			requestLoadingCount++;
			uni.showLoading({
				title: '',
				mask: true
			});
		}
		return uni.request(obj);
	},
	// 发起GET
	get: function(obj) {
		obj.method = 'GET';
		return this.request(obj);
	},
	// 发起POST
	post: function(obj) {
		obj.method = 'POST';
		return this.request(obj);
	},
	//
	onRequestComplete: function(fn) {
		for (let i in requestCompleteHandlers) {
			if (requestCompleteHandlers[i] === fn) {
				//已经有同一个实例, 退出
				return;
			}
		}
		requestCompleteHandlers.push(fn);
	},
	// uploadFile obj.filePath[required]
	// obj.header[optional], obj.success[optional], obj.fail[optional]
	// return res.data.data.url
	uploadFile: function(obj) {
		// obj = Object.assign({url: '/common/upload_qiniu', name: 'file'}, obj);
		let userinfo = this.getCache('userinfo');
		let header = {}
		if (userinfo) {
			header = userinfo.token ? {
				token: userinfo.token
			} : '';
		}
		let tempFilePath = obj.filePath;
		let successCb = obj.success;
		let failCb = obj.fail;

		// #ifdef MP
		// 小程序平台使用getFileSystemManager
		let fileSystemManager = uni.getFileSystemManager();
		fileSystemManager.getFileInfo({
			filePath: tempFilePath,
			success: res => {
				if (getApp().globalData.uploadOssStatus) {
					let size = res.size;
					let md5 = res.digest;
					let nameParts = tempFilePath.split('.');
					let suffix = nameParts[nameParts.length - 1];
					this.post({
						url: getApp().globalData.apiBaseUri + '/xilujob.common/params',
						data: {
							md5: md5,
							name: 'nouse.' + suffix
						},
						success: (ret, response) => {
							//拿到签名，直传alioss
							let key = ret.data.key; //存储路径
							uni.uploadFile({
								name: 'file',
								filePath: tempFilePath,
								formData: {
									key: ret.data.key,
									OSSAccessKeyId: ret.data.id,
									success_action_status: 200,
									policy: ret.data.policy,
									signature: ret.data.signature
								},
								url: getApp().globalData.alioss.endpoint,
								success: res => {
									if (res.statusCode !== 200) {
										if (typeof failCb === 'function') {
											res.data = {
												code: 0,
												msg: '上传阿里云OSS失败'
											};
											failCb(res.data, res);
										} else {
											uni.showToast({
												'title': "上传阿里云OSS失败",
												icon: "none"
											})
										}
										return;
									}
									res.data = {
										code: 1,
										data: {
											url: getApp().globalData
												.storageBaseUri + '/' +
												key
										}
									};
									successCb(res.data, res);
								},
								fail: (res) => {
									if (typeof failCb === 'function') {
										res.data = {
											code: 0,
											msg: '上传阿里云OSS失败'
										};
										failCb(res.data, res);
									} else {
										uni.showToast({
											'title': "上传阿里云OSS失败",
											icon: "none"
										})
									}
								}
							});
						},
						fail: (ret, response) => {
							if (typeof failCb === 'function') {
								return failCb(ret, response);
							}
						}
					});
				} else {
					uni.showLoading({
						title: '上传中'
					})
					uni.uploadFile({
						name: 'file',
						filePath: tempFilePath,
						formData: {

						},
						url: getApp().globalData.apiBaseUri + '/xilujob.common/upload',
						header: header,
						success: res => {
							uni.hideLoading();
							if (res.statusCode !== 200) {
								if (typeof failCb === 'function') {
									res.data = {
										code: 0,
										msg: '上传失败'
									};
									failCb(res.data, res);
								} else {
									uni.showToast({
										'title': "上传失败",
										icon: "none"
									})
								}
								return;
							}
							let data = JSON.parse(res.data);
							if (data.code == 1) {
								data = {
									code: 1,
									data: {
										url: data.data.fullurl
									}
								};
								successCb(data, res);
							} else {
								uni.showToast({
									'title': "上传失败",
									icon: "none"
								})
							}
						},
						fail: (res) => {
							uni.hideLoading();
							if (typeof failCb === 'function') {
								res.data = {
									code: 0,
									msg: '上传失败'
								};
								failCb(res.data, res);
							} else {
								uni.showToast({
									'title': "上传失败",
									icon: "none"
								})
							}
						}
					});
				}
			},
			error: res => {
				console.log(res);
			}
		});
		// #endif

		// #ifndef MP
		// 非小程序平台（APP）使用uni.getFileInfo
		uni.getFileInfo({
			filePath: tempFilePath,
			success: res => {
				if (getApp().globalData.uploadOssStatus) {
					let size = res.size;
					let md5 = res.digest || '';
					let nameParts = tempFilePath.split('.');
					let suffix = nameParts[nameParts.length - 1];
					this.post({
						url: getApp().globalData.apiBaseUri + '/xilujob.common/params',
						data: {
							md5: md5,
							name: 'nouse.' + suffix
						},
						success: (ret, response) => {
							//拿到签名，直传alioss
							let key = ret.data.key; //存储路径
							uni.uploadFile({
								name: 'file',
								filePath: tempFilePath,
								formData: {
									key: ret.data.key,
									OSSAccessKeyId: ret.data.id,
									success_action_status: 200,
									policy: ret.data.policy,
									signature: ret.data.signature
								},
								url: getApp().globalData.alioss.endpoint,
								success: res => {
									if (res.statusCode !== 200) {
										if (typeof failCb === 'function') {
											res.data = {
												code: 0,
												msg: '上传阿里云OSS失败'
											};
											failCb(res.data, res);
										} else {
											uni.showToast({
												'title': "上传阿里云OSS失败",
												icon: "none"
											})
										}
										return;
									}
									res.data = {
										code: 1,
										data: {
											url: getApp().globalData
												.storageBaseUri + '/' +
												key
										}
									};
									successCb(res.data, res);
								},
								fail: (res) => {
									if (typeof failCb === 'function') {
										res.data = {
											code: 0,
											msg: '上传阿里云OSS失败'
										};
										failCb(res.data, res);
									} else {
										uni.showToast({
											'title': "上传阿里云OSS失败",
											icon: "none"
										})
									}
								}
							});
						},
						fail: (ret, response) => {
							if (typeof failCb === 'function') {
								return failCb(ret, response);
							}
						}
					});
				} else {
					uni.showLoading({
						title: '上传中'
					})
					uni.uploadFile({
						name: 'file',
						filePath: tempFilePath,
						formData: {

						},
						url: getApp().globalData.apiBaseUri + '/xilujob.common/upload',
						header: header,
						success: res => {
							uni.hideLoading();
							if (res.statusCode !== 200) {
								if (typeof failCb === 'function') {
									res.data = {
										code: 0,
										msg: '上传失败'
									};
									failCb(res.data, res);
								} else {
									uni.showToast({
										'title': "上传失败",
										icon: "none"
									})
								}
								return;
							}
							let data = JSON.parse(res.data);
							if (data.code == 1) {
								data = {
									code: 1,
									data: {
										url: data.data.fullurl
									}
								};
								successCb(data, res);
							} else {
								uni.showToast({
									'title': "上传失败",
									icon: "none"
								})
							}
						},
						fail: (res) => {
							uni.hideLoading();
							if (typeof failCb === 'function') {
								res.data = {
									code: 0,
									msg: '上传失败'
								};
								failCb(res.data, res);
							} else {
								uni.showToast({
									'title': "上传失败",
									icon: "none"
								})
							}
						}
					});
				}
			},
			error: res => {
				console.log(res);
			}
		});
		// #endif
	},
	uploadFileH5(obj) {
		// obj = Object.assign({url: '/common/upload_qiniu', name: 'file'}, obj);
		let userinfo = this.getCache('userinfo');
		let header = {}
		if (userinfo) {
			header = userinfo.token ? {
				token: userinfo.token
			} : '';
		}
		let tempFilePath = obj.filePath;
		let successCb = obj.success;
		let failCb = obj.fail;
		uni.getFileInfo({
			filePath: tempFilePath,
			success: res => {
				if (getApp().globalData.uploadOssStatus) {
					let size = res.size;
					let md5 = res.digest;
					let nameParts = tempFilePath.split('.');
					let suffix = nameParts[nameParts.length - 1];
					this.post({
						url: getApp().globalData.apiBaseUri + 'xilujob.common/params',
						data: {
							md5: md5,
							name: 'nouse.' + suffix
						},
						success: (ret, response) => {
							//拿到签名，直传alioss
							let key = ret.data.key; //存储路径
							uni.uploadFile({
								name: 'file',
								filePath: tempFilePath,
								formData: {
									key: ret.data.key,
									OSSAccessKeyId: ret.data.id,
									success_action_status: 200,
									policy: ret.data.policy,
									signature: ret.data.signature
								},
								url: getApp().globalData.alioss.endpoint,
								success: res => {
									if (res.statusCode !== 200) {
										if (typeof failCb === 'function') {
											res.data = {
												code: 0,
												msg: '上传阿里云OSS失败'
											};
											failCb(res.data, res);
										} else {
											uni.showToast({
												'title': "上传阿里云OSS失败",
												icon: "none"
											})
										}
										return;
									}
									res.data = {
										code: 1,
										data: {
											url: getApp().globalData
												.storageBaseUri + '/' + key
										}
									};
									successCb(res.data, res);
								},
								fail: (res) => {
									if (typeof failCb === 'function') {
										res.data = {
											code: 0,
											msg: '上传阿里云OSS失败'
										};
										failCb(res.data, res);
									} else {
										uni.showToast({
											'title': "上传阿里云OSS失败",
											icon: "none"
										})
									}
								}
							});
						},
						fail: (ret, response) => {
							if (typeof failCb === 'function') {
								return failCb(ret, response);
							}
						}
					});
				} else {
					uni.showLoading({
						title: '上传中'
					})
					uni.uploadFile({
						name: 'file',
						filePath: tempFilePath,
						formData: {

						},
						url: getApp().globalData.apiBaseUri + '/common/upload',
						header: header,
						success: res => {
							uni.hideLoading();
							//console.log(res);
							if (res.statusCode !== 200) {
								if (typeof failCb === 'function') {
									res.data = {
										code: 0,
										msg: '上传失败'
									};
									failCb(res.data, res);
								} else {
									uni.showToast({
										'title': "上传失败",
										icon: "none"
									})
								}
								return;
							}
							let data = JSON.parse(res.data);
							if (data.code == 1) {
								data = {
									code: 1,
									data: {
										url: data.data.fullurl
									}
								};
								successCb(data, res);
							} else {
								uni.showToast({
									'title': "上传失败",
									icon: "none"
								})
							}
						},
						fail: (res) => {
							uni.hideLoading();
							if (typeof failCb === 'function') {
								res.data = {
									code: 0,
									msg: '上传失败'
								};
								failCb(res.data, res);
							} else {
								uni.showToast({
									'title': "上传失败",
									icon: "none"
								})
							}
						}
					});
				}
			},
			error: res => {
				console.log(res);
			}
		});
	},
	setUserinfo(user) {
		if (!user) {
			return false;
		}
		this.setCache('userinfo', user);
		// 同步更新 globalData.userinfo
		try {
			let app = getApp();
			if (app && app.globalData) {
				app.globalData.userinfo = user;
				console.log('已同步更新 globalData.userinfo');
			}
		} catch (e) {
			console.error('更新 globalData.userinfo 失败:', e);
		}
	},
	// 获取当前登录用户信息
	getUserinfo(forceLogin = false) {
		let userinfo = this.getCache('userinfo');
		if (!userinfo && forceLogin) {
			uni.navigateTo({
				url: '/pages/public/login',
			});
			return false;
		}
		return userinfo;
	},
	//登出
	logout() {
		this.removeCache('userinfo');
		// 同步清空 globalData.userinfo
		try {
			let app = getApp();
			if (app && app.globalData) {
				app.globalData.userinfo = null;
				console.log('已清空 globalData.userinfo');
			}
			uni.$emit(app.globalData.Events.loginOut, {})
		} catch(e) {
			console.error('登出处理失败:', e);
		}
	},
	//检查token是否有效
	checkTokenValid() {
		// 获取当前页面路径
		const pages = getCurrentPages();
		const currentPage = pages[pages.length - 1];
		const currentRoute = currentPage ? currentPage.route : '';

		// 登录页和不需要登录的页面不检查
		const noCheckPages = [
			'pages/public/login',
			'pages/public/privacy_policy',
			'pages/public/privacy-policy',
			'pages/public/privacy_first'
		];

		// 如果当前在不需要检查的页面，直接返回
		if (noCheckPages.includes(currentRoute)) {
			return true;
		}

		// 获取用户信息
		const userinfo = this.getUserinfo();

		// 如果没有用户信息或没有token，说明未登录或token失效
		if (!userinfo || !userinfo.token) {
			console.log('Token失效，强制返回登录页');
			this.logout();
			// 使用reLaunch清空页面栈并跳转到登录页
			uni.reLaunch({
				url: '/pages/public/login'
			});
			return false;
		}

		return true;
	},
	//获取城市
	getCurrentCity() {
		return this.getCache(getApp().globalData.Events.CurrentCityChange, getApp().globalData.defaultCity);
	},
	//设置城市
	setCurrentCity(city) {
		this.setCache(getApp().globalData.Events.CurrentCityChange, city);
		uni.$emit(getApp().globalData.Events.CurrentCityChange, city)
	},
	//获取区县
	getCurrentDistrict(){
		return this.getCache(getApp().globalData.Events.CurrentDistrictChange, getApp().globalData.defaultDistrict);
	},
	//获取经纬度
	getLatLng(obj){
		uni.getLocation({
			type: 'gcj02',
			success: function (res) {
				obj.success(res)
			},
			fail: function(res){
				if(typeof obj.fail == 'function'){
					obj.fail(res)
				}
			}
		});
	},
	//获取定位
	getLocation(){
		var that = this;
		uni.getLocation({
			type: 'gcj02',
			success: function (res) {
				getApp().globalData.location.latitude = res.latitude;
				getApp().globalData.location.longitude = res.longitude;
				that.getCityByLat(res.latitude,res.longitude)
			},
			fail: function(res){
				that.setCurrentCity(that.getCurrentCity());
			}
		});
	},
	getCityByLat(lat,lng){
		this.post({url: 'xilujob.common/get_city_by_lat',loading: false,data: {lat: lat,lng: lng},success: (ret, response) => {
				this.setCurrentCity(ret.data);
			},
			fail: (ret, response) => {
				// uni.showToast({
				// 	title: '城市未开放',
				// 	icon:'none'
				// });
				this.setCurrentCity(this.getCurrentCity());
				return false;
			}
		});
	},

	//打开地图
	async getChooseLocation(params) {
		return await (new Promise(function(resolve, reject) {
			uni.chooseLocation({
				latitude: params.lat,
				longitude: params.lng,
				success:res=>{
					if(res.errMsg=='chooseLocation:ok'){
						resolve({
							name: res.name,
							address: res.address,
							lat: res.latitude,
							lng: res.longitude
						})
					}else{
						uni.showToast({title: '选择失败',icon:'none'})
					}
				},fail:res=>{
					uni.showToast({title: '选择失败',icon:'none'})
				}
			})
		}));
	},

	// 获取缓存数据
	getCache: function(key, defaultValue) {
		let timestampNow = +new Date() / 1e3,
			result = "";
		timestampNow = parseInt(timestampNow);
		try {
			(result = uni.getStorageSync(key + getApp().globalData.appid)).expire > timestampNow || 0 == result
				.expire ? result = result.value : (result = "",
					this.removeCache(key));
		} catch (e) {
			result = void 0 === defaultValue ? "" : defaultValue;
		}
		return result || defaultValue;
	},
	// 设置缓存数据
	setCache: function(key, value, expireInSeconds) {
		let timestampNow = +new Date() / 1e3,
			result = true,
			a = {
				expire: expireInSeconds ? timestampNow + parseInt(expireInSeconds) : 0,
				value: value
			};
		try {
			uni.setStorageSync(key + getApp().globalData.appid, a);
		} catch (e) {
			result = false;
		}
		return result;
	},
	// 移除缓存数据
	removeCache: function(key) {
		let result = true;
		try {
			uni.removeStorageSync(key + getApp().globalData.appid);
		} catch (e) {
			result = false;
		}
		return result;
	},
	//获取年份
	getYears(isJin=false) {
	  let years = isJin?['至今']:[];
	  const currentYear = new Date().getFullYear();
	  for (let i = currentYear; i >= 1900; i--) {
		years.push(i.toString());
	  }
	  return years;
	},
	//获取月份
	getMonths() {
	  let months = [];
	  for (let i = 1; i <= 12; i++) {
		months.push(i < 10 ? '0' + i : i.toString()); // 月份补0显示
	  }
	  return months;
	},
	//支付
	payment(wxconfig,cb,failed) {
		//#ifdef MP-WEIXIN
		uni.requestPayment({
			provider: 'wxpay',
			timeStamp: wxconfig.timeStamp,
			nonceStr: wxconfig.nonceStr,
			package: wxconfig.package,
			signType: wxconfig.signType,
			paySign: wxconfig.paySign,
			success: function(res) {
				uni.showToast({
					title: '支付成功'
				});
				if(typeof cb == 'function') cb()
			},
			fail: function(err) {
				uni.showToast({
					title: '支付失败',
					icon: 'none'
				});
				if(typeof failed == 'function') failed()
			}
		});
		//#endif
	},
	// 获取当前可展示的广告
	getActiveAd(cb) {
		this.get({
			url: 'xilujob.ad/getActiveAd',
			loading: false,
			success: (ret) => {
				if (typeof cb === 'function') {
					cb(ret.data);
				}
			},
			fail: () => {
				if (typeof cb === 'function') {
					cb(null);
				}
				return false;
			}
		});
	},
	// 记录广告点击
	recordAdClick(adId, cb) {
		this.post({
			url: 'xilujob.ad/recordClick',
			loading: false,
			data: {
				ad_id: adId
			},
			success: (ret) => {
				if (typeof cb === 'function') {
					cb(true);
				}
			},
			fail: () => {
				if (typeof cb === 'function') {
					cb(false);
				}
				return false;
			}
		});
	},
	// 静默获取openid, 然后从服务器拉取wx_account信息
	wxLogin(cb) {
		let that = this;
		function executeLogin(cb) {
			uni.login({
				provider: 'weixin',
				success: (auth) => {
					let code = auth.code;
					that.post({
						url: 'xilujob.user/wxlogin',
						loading: true,
						data: {
							code: code,
							platform: 'wxmini',
						},
						success: (ret, response) => {
							let third = ret.data.third;
							console.log(ret.data.userinfo);
							that.setCache('wx_account', third);
							if (third.binding == 1) {
								that.setUserinfo(ret.data.userinfo);
							// 连接WebSocket
								console.log('微信登录成功，正在连接WebSocket...');
								if (chatIM && chatIM.connectSocket) {
									chatIM.connectSocket();
								} else {
									console.warn('WebSocket模块未正确加载');
								}
								if(typeof cb == 'function'){
									cb(ret.data.userinfo)
								}
							}
						},
						fail: (ret, response) => {
							//失败，重试
							setTimeout(function() {
								executeLogin();
							}, 60000);
							return false;
						}
					});
				},
			});
		}
		uni.checkSession({
			success() {
				executeLogin(cb);
			},
			fail() {
				executeLogin(cb);
			}
		});
	},
};